<?php

use app\models\Api;
use app\models\Isp;
use app\models\Package;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
use app\models\Agent;
use app\models\User;
use app\models\KeyMap;
use app\models\Cardtype;
use dosamigos\datepicker\DatePicker;

/**
 * @var $this yii\web\View
 * @var $card app\models\Card
 */

$this->title = '添加/修改订单';
$this->params['breadcrumbs'][] = '物联网卡管理';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);?>
<?php echo Html::activeHiddenInput($order, 'id');?>
<fieldset>
    <legend>分配用户</legend>
    <?php echo $form->field($model, 'user_type')->radioList(['user' => '用户', 'agent' => '代理商']);?>
    <?php echo $form->field($model, 'username')->hint('请填写需要分配给的用户名。');?>
    <?php /*echo $form->field($model, 'id')->hiddenInput();*/?>
    <?php Pjax::begin(['id' => 'pjax_user']);?>
    <?php $userType = Yii::$app->request->get('user_type');
    $username = Yii::$app->request->get('username');
    if (!empty($username)) {
        if ($userType == 'user') {
            /** @var User[] $userList */
            $userList = User::find()
                ->andWhere(['like', 'username', $username])
                ->andWhere(['status' => User::STATUS_OK])
                ->all();
            if (!empty($userList)) {?>
                <div class="form-group">
                    <label class="control-label" for="orderForm-iccid_list">搜索到的用户</label>
                    <div class="help-block">
                        <?php foreach ($userList as $user) {?>
                            <button type="button" class="btn btn-info btn-sm" onclick="$('[name=\'OrderForm[username]\']').val('<?php echo $user->username;?>');"><?php echo Html::encode($user->username);?></button>
                        <?php }?>
                    </div>
                </div>
            <?php } else {?>
                <div class="form-group">
                    <div class="help-block">没有找到用户：<?php echo Html::encode($username);?></button></div>
                </div>
            <?php }
        } elseif ($userType == 'agent') {
            /** @var Agent[] $agentList */
            $agentList = Agent::find()
                ->andWhere(['like', 'username', $username])
                ->andWhere(['status' => Agent::STATUS_OK])
                ->all();
            if (!empty($agentList)) {?>
                <div class="form-group">
                    <label class="control-label" for="orderForm-iccid_list">搜索到的代理商</label>
                    <div class="help-block">
                        <?php foreach ($agentList as $agent) {?>
                            <button type="button" class="btn btn-info btn-sm" onclick="$('[name=\'OrderForm[username]\']').val('<?php echo $agent->username;?>');"><?php echo Html::encode($agent->username);?></button>
                        <?php }?>
                    </div>
                </div>
            <?php } else {?>
                <div class="form-group">
                    <div class="help-block">没有找到代理商：<?php echo Html::encode($username);?></button></div>
                </div>
            <?php }
        }
    }?>
    <?php Pjax::end();?>
</fieldset>
<?php Pjax::begin(['id' => 'pjax_isp']);?>
<?php echo $form->field($order, 'titles');?>
<?php echo $form->field($order, 'isp_id')->dropDownList(ArrayHelper::map(Isp::find()->andWhere(['status' => Isp::STATUS_OK])->andFilterWhere(['api_id' => Yii::$app->request->get('search_api_id')])->all(), 'id', 'name'));?>
<?php Pjax::end();?>
<?php echo $form->field($order, 'type')->dropDownList(ArrayHelper::map(Cardtype::find()->all(), 'id', 'name'), ['prompt' => '选择卡类型']);?>
<?php echo $form->field($order, 'package_id')->dropDownList(ArrayHelper::map(Package::find()->all(), 'id', 'name'), ['prompt' => '选择套餐']);?>


<?php echo $form->field($order, 'price')->textInput(['readonly'=>'true']);?>




<?php echo $form->field($order, 'number');?>
<?php echo $form->field($order, 'amount')->textInput(['readonly'=>'true']);?>
<?php echo $form->field($order, 'cardfee');?>
<?php echo $form->field($order, 'payment_type')->radioList(['2'=>'后付费','1'=>'预付费']);?>
<?php  if($order->payment_type==1){ }?>
<div class="form-group isdate">
    <?php $order->term_length_unit = 3; ?>
    <?php echo $form->field($order, 'term_length_unit')->radioList(['3'=>'月']);?>
    <?php echo $form->field($order, 'term_length');?>
</div>

<?php echo $form->field($order, 'need_invoice')->radioList(KeyMap::getValues('yes_no'));?>


<?php echo $form->field($modela, 'file')->fileInput();?>
<?= Html::img($imgurl, ['class' => 'imgurl']);?>
<div class="form-group">
    <div class="col-lg-offset-1 col-lg-11">
        <button type="button" class="btn btn-default" onclick="window.history.go(-1);"><i class="ace-icon fa fa-arrow-left bigger-110"></i>返回</button>
        <button class="btn btn-primary"><i class="ace-icon fa fa-check bigger-110"></i>保存</button>
        <button type="reset" class="btn btn-warning"><i class="ace-icon fa fa-undo bigger-110"></i>重置</button>
    </div>
</div>
<?php $form->end();?>
<script>
    window.onload=function (){
        //var pa = $('[name="Order[payment_type]"]').val();
        var pa = "<?php echo $order->payment_type; ?>";
        if(pa==1){
            $(".isdate").show();
        }else{
            $(".isdate").hide();
        }



    }

    function pageInit() {


        $('[name="Order[package_id]"]').change(function () {
            var id = $(this).val();
            var usertype = $('[name="OrderForm[user_type]"]:checked').val();
            var username = $('[name="OrderForm[username]"]').val();
            $.ajax({
                url:"packageprice?id="+id+"&usertype="+usertype+"&username="+username,    //请求的url地址
                dataType:"json",   //返回格式为json
                async:true,//请求是否异步，默认为异步，这也是ajax重要特性
                type:"get",
                success:function(req){
                    if(req.code==1){
                        var number = $('[name="Order[number]"]').val();
                        if(number==''){
                            $('[name="Order[amount]"]').val(req.data.price);
                        }else{
                            $('[name="Order[amount]"]').val(accMul(req.data.sale_price,number));
                        }
                        $('[name="Order[price]"]').attr("value",req.data.sale_price);
                    }else if(req.code==1001){
                        alert(req.msg);
                        $('[name="Order[price]"]').attr("value","");
                        //location.href="<?= Url::toRoute('user/user-list');?>";
                    }else if(req.code==1002){
                        alert(req.msg);
                        $('[name="Order[price]"]').attr("value","");
                        //location.href="<?= Url::toRoute('user/agent-list');?>";
                    }
                }
            });

        })
        $('[name="Order[payment_type]"]').click(function () {
            var status = $(this).val();
            if(status==1){
                //预付费
                $(".isdate").show();
            }else{
                //后付费
                $('[name="Order[active_time]"]').val("");
                $('[name="Order[term_length_unit]"]').val("0");
                $('[name="Order[term_length]"]').val("0");
                $('[name="Order[term_end_time]"]').val("");
                $(".isdate").hide();
            }


        })
        $('[name="Order[term_length]"]').keyup(function () {
            var num = $(this).val();

            /*var nums = num*1+actievs;
            var ends = "+"+nums+"month";*/
            //alert(ends);
            // $('[name="Order[term_end_time]"]').datepicker('setDate',new Date("2018-8-6"));

            /*$('[name="Order[term_end_time]"]').datepicker('setDate',ends);
            $('[name="Order[term_end_time]"]').datepicker('format','yyyy-mm-dd');*/
            //$('[name="Order[term_end_time]"]').datepicker({dateFormat:'yyyy-mm-dd',defaultDate: "+1m"});
            /*$('[name="Order[term_end_time]"]').datepicker('setDate','+1m').formatDate('format','yyyy-mm-dd');*/




        })
        //console.log(GetDay(10));
        function GetDay(day) {
            var time = new Date();
            time.setDate(time.getDate() + day);//获取Day天后的日期
            var y = time.getFullYear();
            var m = time.getMonth() + 1;//获取当前月份的日期
            alert(m);
            var d = time.getDate();
            return y + "-" + m + "-" + d;
        }
        function getLastDayOfMonth (time) {
            const dd = new Date(time)
            const curMonth = dd.getMonth()
            //  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1
            dd.setMonth(curMonth + 1)
            // 将日期设置为0, 返回当月最后一天日期， 将日期设置为1，返回下一个月第一天日期
            dd.setDate(0)
            return timeToStr(dd)
        }
        function   DateAdd(interval,number,date)
        {
            /*
              *   功能:实现VBScript的DateAdd功能.
              *   参数:interval,字符串表达式，表示要添加的时间间隔.
              *   参数:number,数值表达式，表示要添加的时间间隔的个数.
              *   参数:date,时间对象.
              *   返回:新的时间对象.
              *   var   now   =   new   Date();
              *   var   newDate   =   DateAdd( "d ",5,now);
              *---------------   DateAdd(interval,number,date)   -----------------
              */
            date   =   new   Date(date);
            switch(interval){case   "m "   :   {
                    date.setMonth(date.getMonth()+number);
                    return   date.toLocaleDateString().replace("\/","-").replace("\/","-");
                    break;
                }
            }
        }
        //alert(getLastDayOfMonth('2019-07'));
        //加两个月.
        //var   now   =   new   Date('2019-07-20');
        //console.log(now);
        //newDate   =   DateAdd( "m ",2,now);
        //newDate   =   DateAdd( "m ",2,'2019-07-20');
        //alert(newDate);


        $(".imgurl").css("width","150px");
        $('[name="OrderForm[username]"]').keyup(function () {
        //$("#OrderForm-username").keyup(function () {
            var username = $(this).val();
            $.pjax.reload('#pjax_user', {
                history: false,
                push: false,
                url: '<?php echo Url::current(['ajax' => 1]);?>&user_type=' + $('[name="OrderForm[user_type]"]:checked').val() + '&username=' + encodeURIComponent(username)
            });
        });
        $('[name="Order[price]"]').change(function(){
            var price = $(this).val();
            var number = $('[name="Order[number]"]').val();
            if(number==''){
                $('[name="Order[amount]"]').val(price);
            }else{
                $('[name="Order[amount]"]').val(accMul(price,number));
            }
        });
        $('[name="Order[number]"]').keyup(function(){
            var number = $(this).val();
            var price = $('[name="Order[price]"]').val();
            if(price==''){
                $('[name="Order[amount]"]').val(price);
            }else{
                $('[name="Order[amount]"]').val(accMul(price,number));
            }
        });
        
        //处理js乘法精度方法
        function accMul(arg1,arg2){
            var m=0,s1=arg1.toString(),s2=arg2.toString();
            try{m+=s1.split(".")[1].length}catch(e){}
            try{m+=s2.split(".")[1].length}catch(e){}
            return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
        }

    }

</script>
